#!/bin/bash

set -x

set -eo pipefail

# Remove any 'environment.yml' or 'requirements.txt' files which may
# have been carried over from the base image so we don't reinstall
# packages which have already been installed. This could occur where
# an S2I build was used to create a new base image with pre-installed
# Python packages, with the new image then subsequently being used as a
# S2I builder base image.

rm -f "/home/${NB_USER}/environment.yml"
rm -f "/home/${NB_USER}/requirements.txt"

# Copy injected files to target directory.

cp -Rf /tmp/src/. "/home/${NB_USER}"

rm -rf /tmp/src

# Install any Python modules. If we find an 'environment.yml' file we
# assume we should use 'conda' to install packages. If 'requirements.txt'
# use 'pip' instead.

if [ -f "/home/${NB_USER}/environment.yml" ]; then
    mamba env update --name root --file "/home/${NB_USER}/environment.yml"
    mamba clean --all -f -y
else
    if [ -f "/home/${NB_USER}/requirements.txt" ]; then
        pip --no-cache-dir install -r "/home/${NB_USER}/requirements.txt"
    fi
fi

# Fix up permissions on home directory and Python installation so that
# everything is still writable by 'users' group.

fix-permissions "${CONDA_DIR}"
fix-permissions "/home/${NB_USER}"
